import java.io.*;
import java.net.*;
import java.util.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionProcessor3 implements Runnable
{
  private EM_Server3 server;

  private Socket socket;

  private DataInputStream din;

  private DataOutputStream dout;

  public ConnectionProcessor3( EM_Server3 server, Socket socket ) {
    this.server = server;
    this.socket = socket;

    new Thread( this ).start();
  }
  
  public void run() {
    try {
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );

      Class.forName("com.mysql.jdbc.Driver");
      Connection connect = DriverManager.getConnection("jdbc:mysql://localhost/em?"+"user=user&password=password");
      
      //informamos de cuántos experimentos han finalizado.
      Statement statement_count = connect.createStatement();
      ResultSet n_finalitzats = statement_count.executeQuery("SELECT COUNT(id) FROM em.EXPERIMENTS WHERE STATUS = 'Finalitzat';");
      n_finalitzats.next();
      int count = n_finalitzats.getInt("COUNT(id)");
      dout.writeInt(count);

      //Los enviamos uno a uno:
      Statement statement_finalitzats = connect.createStatement();
      ResultSet finalitzats = statement_finalitzats.executeQuery("SELECT * FROM em.EXPERIMENTS WHERE STATUS = 'Finalitzat';");
      while(finalitzats.next()){

	dout.writeUTF(finalitzats.getString("IDEXPERIMENT"));
	dout.writeUTF(finalitzats.getString("RESULTATS"));

      }
      
      //Necesitamos el ok para borrar.

      String ok = din.readUTF();
      if (ok.equals("Todo bien!")){
	GestorBD gestor = new GestorBD();
	gestor.modificar("em","user","password","DELETE FROM em.EXPERIMENTS WHERE STATUS = 'Finalitzat'");
      }
   
      } catch( Exception e ) {
      try {
        socket.close();
      } catch( IOException ie2 ) {
        System.out.println( "Error closing socket "+socket );
      }

      server.removeConnection( this );

      System.out.println( "Closed connection from socket "+socket );
    }
  }

}
